2B. Data Modeling (E-Commerce)
1: Ecommerce App: Data Flow Diagram
2. Create Models

User Model
import mongoose from 'mongoose';
const userSchema = mongoose.Schema(
{
username: {
type: String,
required: [true, "this is required field"],
unique: true,
max: [10, "username should not exceed 10 characters"],
lowercase: true,
trim: true
},
email: {
type: String,
required: [true, "this is required field"],
unique: true,
lowercase: true
},
email: {
type: String,
required: [true, "this is required field"],
unique: true,
minLength: [5, "password should not be less than 5"],
maxLength: [15, "password should not exceed 10 characters"]
},
address: {
street: String,
city: String,
State: String,
zip: String,
landmark: String,
country: String
},
createdAt: {
type: Date,
default: Date.now,
}
}, { timestamps: true }
)
const User = mongoose.model("User", userSchema)
export default User
Category Model
import mongoose from 'mongoose';
const categorySchema = mongoose.Schema(
{
name: {
type: String,
unique: true,
trim: true,
required: true
},
description: {
type: String,
trim: true
}
}, { timestamps: true }
)
const Category = mongoose.model("Category", categorySchema);
export default Category;
Product Model
import mongoose from 'mongoose';
const productSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true
},
price: {
type: Number,
required: true,
min: 0
},
description: {
type: String,
required: true,
trim: true
},
category: {
type: Schema.Types.ObjectId,
ref: "Category"
},
stock: {
type: Number,
required: true,
min: 0
},
images: [String],
createdAt: {
type: Date,
default: Date.now,
}
}
)
const Product = mongoose.model("Product", productSchema);
export default Product;
Order Model
import mongoose from 'mongoose';
const orderSchema = mongoose.Schema(
{
user_details: {
type: Schema.Types.ObjectId,
ref: "User",
required: true
},
products: [
{
product: { type: Schema.Types.ObjectId, ref: "Product", required: true },
quantity: { type: Number, min: 1, max: 10, required: true }
}
],
total_amount: {
type: Number,
required: true
},
status: {
type: String,
enum: ['pending', 'cancelled', 'delivered', 'shipped']
},
createdAt: {
type: Date,
default: Date.now,
},
createdAt: {
type: Date,
}
}
)
const Order = mongoose.model("Order", orderSchema)
export default Order;
or
import mongoose from "mongoose"
import { product } from "./product.models"
const orderItemsSchema = new mongoose.Schema({
productId:{
type:mongoose.Schema.Types.ObjectId,
ref:"Product",
},
quantity:{
type:Number,
required:true
}
},{timestamps:true})
const orderSchema = new mongoose.Schema({
orderPrice:{
type:String,
required:true,
},
customer:{
type:mongoose.Schema.Types.ObjectId,
ref:"User",
},
orderItems:{
type:[orderItemsSchema]
},
address:{
type:String,
required:true
}
},{timestamps:true})
export const order = mongoose.model("order",orderSchema)